<template>
  <div class="app-container historyData">
    <search-form
      ref="header"
      :search-data="ruleForm"
      :search-form="searchData"
      :search-handle="searchHandle"
    >
      <slot>
        <el-popover placement="bottom" :width="240" trigger="click">
          <template #reference>
            <el-button size="mini" style="float:right;padding:7px 10px;">
              <i
                class="el-icon-setting"
                style="font-size:16px;margin-right:5px;"
              ></i
              >设置列</el-button
            >
          </template>
          <div style="max-height:350px;width:100%;overflow:auto;">
            <el-checkbox-group v-model="headChecked">
              <template v-for="item in checkboxHeads" :key="item">
                <el-checkbox
                  :label="item"
                  style="margin:10px 8px 0 0;"
                ></el-checkbox>
              </template>
            </el-checkbox-group>
          </div>
          <div class="drop-footer m_t10" style="text-align:center;">
            <el-button type="primary" size="mini" @click="handleSetTitle"
              >确定</el-button
            >
          </div>
        </el-popover>
      </slot>
    </search-form>
    <el-table
      :data="tableData"
      style="width: 100%;"
      :header-cell-style="{
        padding: '10px 0',
        color: 'rgb(0, 127, 235)',
        backgroundColor: '#fff',
      }"
      :height="tableHeight"
      v-loading="loading"
      size="medium"
    >
      <el-table-column prop="heatSourceName" label="热源名称"></el-table-column>
      <el-table-column
        prop="heatStationName"
        label="换热站"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="systemName"
        label="系统名称"
        align="center"
      ></el-table-column>
      <!-- <el-table-column
        prop="userType"
        label="用户类型"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="heatModel"
        label="供热模式"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="heatType"
        label="节能类型"
        align="center"
      ></el-table-column> -->
      <el-table-column
        prop="date"
        label="数据时间"
        align="center"
        width="160"
        :formatter="filterTime"
      ></el-table-column>
      <el-table-column
        prop="控制模式"
        label="控制模式"
        align="center"
        :formatter="formatKZ"
      >
      </el-table-column>
      <el-table-column
        prop="水箱液位"
        label="水箱液位"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="手动给定"
        label="手动给定"
        align="center"
      ></el-table-column>
      <template v-for="(item, index) in tableColumn" :key="index">
        <el-table-column
          :label="item.name"
          :prop="item.prop"
          align="center"
          v-if="!item.isShow"
        >
          <template v-for="(child, cIdx) in item.child" :key="cIdx">
            <el-table-column
              v-if="!child.isShow"
              :label="child.name"
              align="center"
            >
              <template #default="scope">
                <span v-html="valueFormatter(scope.row, child.prop)"> </span>
              </template>
            </el-table-column>
          </template>
        </el-table-column>
      </template>
    </el-table>
  </div>
</template>
<script>
import { onMounted, reactive, toRefs } from "vue";
import { useStore } from "vuex";
import { getSendList, getJieNengType } from "@/api/remoteSend";
import { getHistoryDataNew } from "@/api/historydata";
import searchForm from "@/components/SearchForm/index.vue";
import utils from "./index";
import heightMinxin from "@/utils/tableHeight.mixin";
import { parseTime } from "@/utils/index";
export default {
  name: "runData",
  mixins: [heightMinxin],
  components: { searchForm },
  setup() {
    const store = useStore();
    const state = reactive({
      ruleForm: {
        heatSourceId: "",
        heatingType: "",
        heatSystemIds: [],
        beginTime: "",
        endTime: "",
      },
      searchData: [
        {
          type: "Select",
          prop: "heatSourceId",
          options: [],
          placeholder: "选择热源",
          change: () => {
            state.ruleForm.heatSystemIds = [];
            state.searchData[2].options = [];
            getHeatSystemData();
          },
        },
        {
          type: "Select",
          prop: "heatingType",
          options: [],
          placeholder: "节能类型",
          change: () => {
            state.ruleForm.heatSystemIds = [];
            state.searchData[2].options = [];
            getHeatSystemData();
          },
        },
        {
          type: "Select",
          prop: "heatSystemIds",
          multiple: true,
          filterable: true,
          options: [],
          collapse: true,
          width: 240,
          placeholder: "选择系统",
          change: () => {},
        },
        {
          type: "DateTime",
          prop: "beginTime",
          placeholder: "开始时间",
        },
        {
          type: "DateTime",
          prop: "endTime",
          placeholder: "开始时间",
        },
      ],
      searchHandle: [
        {
          label: "搜索",
          type: "primary",
          handle: () => {
            getList();
          },
        },
      ],
      loading: false,
      tableColumn: [],
      tableData: [],
      headChecked: [],
      checkboxHeads: [],
    });
    onMounted(() => {
      state.ruleForm.endTime = parseTime(new Date(), "{y}-{m}-{d} {h}:{i}:{s}");
      var curTime = new Date().getTime();
      var startDate = curTime - 1 * 60 * 60 * 1000;
      state.ruleForm.beginTime = parseTime(
        startDate,
        "{y}-{m}-{d} {h}:{i}:{s}"
      );
      init();
    });
    const init = async () => {
      await getHeatSourceData();
      const typeArr = await getHeatTypeList("heatingType");
      state.searchData[1].options = typeArr;
      await getTableHeads();
      getList();
    };

    const formatKZ = (row) => {
      if (typeof row.控制模式 !== "undefined") {
        if (row.控制模式 == 0) {
          return "手动";
        }
        if (row.控制模式 == 1) {
          return "分时开度";
        }
        if (row.控制模式 == 2) {
          return "分时温度";
        }
        if (row.控制模式 == 3) {
          return "分时流量";
        }
        if (row.控制模式 == 4) {
          return "恒定流量";
        }
        if (row.控制模式 == 5) {
          return "点对点温度";
        }
      } else {
        return null;
      }
    };
    /**
     * 格式化数据
     */
    const filterTime = (row) => {
      return parseTime(row.date, "{y}-{m}-{d} {h}:{i}");
    };
    /**获取热源列表 */
    const getHeatSourceData = () => {
      const { sourceData } = store.getters;
      state.searchData[0].options = sourceData;
      if (sourceData.length > 0) {
        state.ruleForm.heatSourceId = sourceData[0].value;
        getHeatSystemData();
      }
    };

    const getHeatTypeList = (type) => {
      return new Promise((resolve) => {
        getJieNengType({ typeName: type }).then((res) => {
          if (res.data.success) {
            const result = res.data.data.map((item) => {
              return { label: item[type], value: item[type] };
            });
            resolve(result);
          }
        });
      });
    };
    // /**获取系统数据 */
    const getHeatSystemData = () => {
      const { heatSourceId, heatingType } = state.ruleForm;
      getSendList({ heatSourceId, heatingType }).then((res) => {
        if (res.data.success) {
          let data = res.data.data;
          const result = data.map((item) => {
            return { label: item.name, value: item.id };
          });
          state.searchData[2].options = result;
          if (result.length > 0) {
            let list = result.slice(0, 5);
            state.ruleForm.heatSystemIds = list.map((v) => v.value);
          }
        }
      });
    };

    const getList = () => {
      state.loading = true;
      const { heatSystemIds, beginTime, endTime } = state.ruleForm;
      let systemData = state.searchData[2].options;
      let idsArr = [];
      if (heatSystemIds.length == 0) {
        idsArr = systemData.map((item) => item.value);
      } else {
        idsArr = heatSystemIds;
      }
      let endTimes = endTime
        ? parseTime(endTime, "{y}-{m}-{d} {h}:{i}:{s}")
        : "";

      let beginTimes = beginTime
        ? parseTime(beginTime, "{y}-{m}-{d} {h}:{i}:{s}")
        : "";
      getHistoryDataNew({
        heatSystemIds: idsArr,
        beginTime: beginTimes,
        endTime: endTimes,
      }).then((res) => {
        if (res.data.success) {
          state.loading = false;
          state.tableData = res.data.data;
        }
      });
    };

    const valueFormatter = (row, prop) => {
      if (prop == "一次温差") {
        if (row["一供温度"] !== undefined && row["一回温度"] !== undefined) {
          let num = row["一供温度"] - row["一回温度"];
          return num.toFixed(2);
        } else {
          return null;
        }
      }
      if (prop == "一次压差") {
        if (row["一供压力"] != undefined && row["一回压力"] != undefined) {
          let oneYaValue = row["一供压力"] - row["一回压力"];
          return oneYaValue.toFixed(2);
        } else {
          return null;
        }
      }
      if (prop == "二次温差") {
        if (row["二供温度"] != undefined && row["二回温度"] != undefined) {
          let num1 = row["二供温度"] - row["二回温度"];
          return num1.toFixed(2);
        } else {
          return null;
        }
      }
      if (prop == "二次压差") {
        if (row["二供压力"] != undefined && row["二回压力"] != undefined) {
          let num = row["二供压力"] - row["二回压力"];
          return num.toFixed(2);
        } else {
          return null;
        }
      }
      if (row[prop] !== undefined) {
        return row[prop];
      } else {
        return null;
      }
    };
    const getTableHeads = () => {
      const { tableTitle } = utils;
      const result = tableTitle.map((item) => {
        if (item.child) {
          const child = item.child.map((v) => {
            return { ...v, isShow: false };
          });
          item.child = child;
        }

        item.isShow = false;

        return item;
      });
      state.tableColumn = result;
      state.checkboxHeads = utils.getNameArr(tableTitle);
    };

    /**自定义列设置 */
    const handleSetTitle = async () => {
      let list = state.tableColumn;
      let checkArr = state.headChecked;
      for (let i = 0; i < list.length; i++) {
        let item = list[i];
        if (item.child) {
          for (let j = 0; j < item.child.length; j++) {
            const { prop } = item.child[j];
            if (checkArr.includes(prop)) {
              item.child[j]["isShow"] = true;
            } else {
              item.child[j]["isShow"] = false;
            }
          }
          const flag = await filterFlag(item.child);

          if (flag) {
            item.isShow = true;
          } else {
            item.isShow = false;
          }
        }
      }
      state.tableColumn = list;
    };

    const filterFlag = (arr) => {
      const result = arr.every((v) => v.isShow === true);
      return result;
    };

    return {
      ...toRefs(state),
      formatKZ,
      filterTime,
      handleSetTitle,
      valueFormatter,
    };
  },
};
</script>
<style lang="less"></style>
